﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Models;

namespace MinistryStandardPlatformWeb.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        private MSPDataContext context = new MSPDataContext();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login(String ReturnUrl)
        {
            if (CommonFunctions.GetLoginUser() != null)
            {
                //要实时更新检查菜单权限
                UserＭodel model = CommonFunctions.GetLoginUser();
                List<string> rights = context.MenuRights.Where(r => r.UserId == model.UserId && r.RightType ==null).Select(u => u.MenuId).ToList();
                model.MenuRights = rights;
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                            model.UserId,
                            DateTime.Now,
                            DateTime.Now.Add(FormsAuthentication.Timeout),
                            true,
                            model.ToString());

                Response.Cookies[FormsAuthentication.FormsCookieName].Value = FormsAuthentication.Encrypt(ticket);
                Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(7);
                return RedirectToAction("Index", "MonitorCenter");
            }
            LoginModel model1=new LoginModel()
            {
              _ReturnUrl=ReturnUrl
            };
            return View(model1);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                List<LoginUsers> users = context.LoginUsers.Where(u => u.UserId == model.UserId && u.LoginPassword == model.Password).ToList();
                if (users.Count()==1)
                {
                    if (users[0].userState == "启用")
                    {
                        UserＭodel user = new UserＭodel();
                        user.UserId = users[0].UserId;
                        user.UnitId = users[0].CustomerID;
                        user.UnitName = users[0].CustomerName;

                        List<string> rights = context.MenuRights.Where(r => r.UserId == model.UserId && r.RightType==null).Select(u => u.MenuId).ToList();
                        user.MenuRights = rights;

                        //设置用cookie方式验证
                        FormsAuthentication.SetAuthCookie(model.UserId, model.RememberMe);

                        //将认证信息写入到cookie中
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                            model.UserId,
                            DateTime.Now,
                            DateTime.Now.Add(FormsAuthentication.Timeout),
                            true,
                            user.ToString(),
                            FormsAuthentication.FormsCookiePath);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                        cookie.Path = FormsAuthentication.FormsCookiePath;
                        if (model.RememberMe)
                        {
                            cookie.Expires = DateTime.Now.AddDays(7);
                        }
                        if (Response.Cookies[FormsAuthentication.FormsCookieName] == null)
                        {
                            Response.Cookies.Add(cookie);
                        }
                        else
                        {
                            Response.Cookies[FormsAuthentication.FormsCookieName].Value = FormsAuthentication.Encrypt(ticket);
                            Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(7);
                        }
                        if (Url.IsLocalUrl(model._ReturnUrl) && model._ReturnUrl.Length > 1 && model._ReturnUrl.StartsWith("/")
                            && !model._ReturnUrl.StartsWith("//") && !model._ReturnUrl.StartsWith("/\\"))
                        {
                            string c=model._ReturnUrl.Substring(1,model._ReturnUrl.LastIndexOf('/')-1);
                            string a=null;
                            string _id=null;
                            if (model._ReturnUrl.Contains('?'))
                            {
                                a = model._ReturnUrl.Substring(model._ReturnUrl.LastIndexOf('/') + 1, model._ReturnUrl.IndexOf('?') - model._ReturnUrl.LastIndexOf('/') - 1);
                                if (model._ReturnUrl.Contains('&'))
                                {
                                    _id = model._ReturnUrl.Substring(model._ReturnUrl.IndexOf('?') + 1,model._ReturnUrl.IndexOf('&')-model._ReturnUrl.IndexOf('?')-1);
                                }
                                else
                                {
                                    _id = model._ReturnUrl.Substring(model._ReturnUrl.IndexOf('?') + 1);
                                }
                            }
                            else
                            {
                                a = model._ReturnUrl.Substring(model._ReturnUrl.LastIndexOf('/') + 1);
                            }
                            return RedirectToRoute(new { controller = c, action = a, id = _id });
                        }
                        else
                        {
                            //Response.Redirect("/MonitorCenter/Index/");
                            //FormsAuthentication.RedirectFromLoginPage("admin", true);
                            return RedirectToAction("Index", "MonitorCenter");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "该账户已停用");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名或密码错误");
                }
            }

            // If we got this far, something failed, redisplay form
            model.Password = string.Empty;
            return View(model);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            //Session["IsLogin"] = "False";
            return RedirectToAction("Login", "Login");
        }

        public ActionResult VerificationCode(string id)
        {
            GenerateVerificationCode validateCode = new GenerateVerificationCode();
            byte[] bytes = validateCode.CreateImage();
            Session["VerificationCode"] = validateCode.RandomCode;
            return File(bytes, @"image/gif");
        }

        public string GetVerificationCode()
        {
            return Session["VerificationCode"].ToString();
        }
    }
}
